package org.darkforest.ucenter.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.MathUtil;
import org.darkforest.common.util.Page;
import org.darkforest.dao.mapper.MemberRemindSettingMapper;
import org.darkforest.dao.mapper.MobileUserTokenMapper;
import org.darkforest.dao.mapper.WebChatScanMapper;
import org.darkforest.enums.MemberType;
import org.darkforest.model.*;
import org.darkforest.ucenter.service.PointService;
import org.darkforest.vo.MemberBase;
import org.darkforest.vo.MemberSearchBean;
import org.darkforest.vo.WapAjaxMsg;
import org.darkforest.vo.WxUserDetailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by valentina on 15/3/7.
 * wap端用户操作类，在基本用户操作之外增加wap端功能
 */
@Service("wapMemberServiceImpl")
public class WapMemberServiceImpl extends MemberServiceImpl {

    @Autowired
    private MobileUserTokenMapper mobileUserTokenMapper;            //移动端用户令牌

    @Autowired
    private PointService pointService;

    @Autowired
    private WebChatScanMapper scanMapper;

    @Autowired
    private MemberRemindSettingMapper memberRemindSettingMapper;

    @Override
    public WapAjaxMsg<MemberBase> regist(Member member) {
        WapAjaxMsg<MemberBase> msg = super.regist(member);
        if (msg.getError() == null) {
            //没有异常，添加token
            String token = getNewToken(msg.getDatas().getUserId(), msg.getDatas().getUserName(), "wap");
            msg.getDatas().setKey(token);
        }
        return msg;
    }

    @Override
    public WapAjaxMsg<MemberBase> login(String userName, String pwd) {
        WapAjaxMsg<MemberBase> msg = super.login(userName, pwd);
        if (msg.getError() == null) {
            String token = getNewToken(msg.getDatas().getUserId(), msg.getDatas().getUserName(), "wap");
            msg.getDatas().setKey(token);
        }
        return msg;
    }

    @Override
    public WapAjaxMsg<MemberBase> logout(String userName, String key) {
        WapAjaxMsg msg = super.logout(userName, key);
        if (msg.getError() == null) {
            MobileUserToken token = new MobileUserToken();
            token.setMemberName(userName);
            token.setToken(key);
            token.setClientType("wap");
            mobileUserTokenMapper.deleteByCondition(token);
        }
        return msg;
    }

    /**
     * 生成token，存入数据库并返回
     *
     * @param userId
     * @param userName
     * @param client
     * @return
     */
    private String getNewToken(Integer userId, String userName, String client) {
        MobileUserToken token = new MobileUserToken();

        String tokenStr = DigestUtils.md5Hex(userName + DateUtil.unixTimeStamp() + MathUtil.getRandom(6));
        token.setMemberId(userId);
        token.setMemberName(userName);
        token.setClientType(client);
        token.setToken(tokenStr);
        token.setLoginTime(DateUtil.unixTimeStampInt().intValue());

        int res = mobileUserTokenMapper.insert(token);
        if (res > 0) {
            return tokenStr;
        }
        return null;
    }

    @Override
    public Page<Member> getMemberListForAdmin(MemberSearchBean param) {
        return null;
    }


    /**
     * 根据从微信拉取的用户信息，注册或更新用户信息
     * 1、注册自动填写trueName，头像，性别等信息
     * 2、对比
     * @param userInfo 微信用户信息
     * @param rid 推荐人ID
     * @return
     */
    @Override
    public MemberWithBLOBs saveWxUserInfo(WxUserDetailInfo userInfo, String rid) {
        MemberWithBLOBs memberWithBLOBs = new MemberWithBLOBs();
        Member member_db = memberMapper.getMemberByWxId(userInfo.getOpenId());

        if (member_db==null) {

            //-----通过分享进来的用户也走扫码流程 start---//
            if(StringUtils.isNotEmpty(rid)){
                WebChatScan ws = new WebChatScan();
                ws.setOpenid(userInfo.getOpenId());
                ws.setRecommendId(rid);
                ws.setOptTime(new Date());
                scanMapper.insertSelective(ws);
            }
            //-----通过分享进来的用户也走扫码流程 end---//


            memberWithBLOBs.setMemberTruename(userInfo.getNickName());          //修改微信昵称为真实姓名，用户名留给pc端使用
            memberWithBLOBs.setMemberName(userInfo.getNickName());
            memberWithBLOBs.setMemberAvatar(userInfo.getAvatar());
            memberWithBLOBs.setMemberSex(userInfo.getSex());
            memberWithBLOBs.setMemberWxOpenid(userInfo.getOpenId());
            memberWithBLOBs.setMemberWxNickName(userInfo.getNickName());
            memberWithBLOBs.setMemberEmail("");
            memberWithBLOBs.setMemberPasswdConfirm("");
            memberWithBLOBs.setMemberPasswd("");
            memberWithBLOBs.setMemberEmailBind(0);
            memberWithBLOBs.setMemberMobileBind(0);
            memberWithBLOBs.setMemberLoginNum(0);
            memberWithBLOBs.setMemberTime(DateUtil.unixTimeStamp());
            memberWithBLOBs.setMemberLoginTime(DateUtil.unixTimeStamp());
            memberWithBLOBs.setMemberOldLoginTime(DateUtil.unixTimeStamp());
            memberWithBLOBs.setMemberPoints(0);
            memberWithBLOBs.setAvailablePredeposit(new BigDecimal(0));
            memberWithBLOBs.setFreezePredeposit(new BigDecimal(0));
            memberWithBLOBs.setInformAllow(true);
            memberWithBLOBs.setIsBuy(true);
            memberWithBLOBs.setIsAllowtalk(true);
            memberWithBLOBs.setMemberState(true);
            memberWithBLOBs.setMemberCredit(0);
            memberWithBLOBs.setMemberSnsvisitnum(0);
            memberWithBLOBs.setMemberCoin(BigDecimal.ZERO);
            memberWithBLOBs.setMemberTypeEnum(MemberType.NORMAL);           //设置会员类型默认为1：普通会员

            /*从微信扫码关注表中搜索是否存在openid 如果存在就获取该openid的推荐人ID*/
            WebChatScan webChatScan = scanMapper.selectByOpenid(userInfo.getOpenId());

            //注册时，无推荐人时recommend_id存0，有推荐人时存储推荐人id，并且同时存储recommend_name
            Member parent_member = new Member();
//
            Integer recommendId = webChatScan==null? 0 : Integer.parseInt(webChatScan.getRecommendId());
            parent_member = memberMapper.findMemberInfoByPrimaryKey(webChatScan==null?"0":webChatScan.getRecommendId());
            if (webChatScan != null && parent_member!=null) {
                memberWithBLOBs.setRecommendId(recommendId);
                memberWithBLOBs.setRecommendName(parent_member.getMemberTruename());
                //设置会员的path add by chenyu
                memberWithBLOBs.setPath(recommendId+","+parent_member.getRecommendId());
                memberWithBLOBs.setProxyPath(parent_member.getProxyPath());
            } else {
                memberWithBLOBs.setRecommendId(0);
                memberWithBLOBs.setRecommendName("");
                memberWithBLOBs.setPath("0,0");
                memberWithBLOBs.setProxyPath("0,0,0");
            }
            memberMapper.insert(memberWithBLOBs);

            //初始化配置用户提醒设置表
            MemberRemindSetting record = new MemberRemindSetting();
            record.setrMemberId(memberWithBLOBs.getMemberId());
            record.setrContactsRemindSwtich("1");
            record.setrOfferRemindSwtich("1");
            record.setrSystemMsgSwitch("1");
            memberRemindSettingMapper.insert(record);

            pointService.addPointForRegist(recommendId, parent_member==null?null:parent_member.getMemberTruename(),parent_member==null?null:parent_member.getMemberType(), memberWithBLOBs.getMemberId(), memberWithBLOBs.getMemberTruename(), memberWithBLOBs.getMemberAvatar());

        } else {
            memberWithBLOBs.setMemberId(member_db.getMemberId());
            memberWithBLOBs.setMemberName(userInfo.getNickName());
            memberWithBLOBs.setMemberTruename(userInfo.getNickName());
            memberWithBLOBs.setMemberAvatar(member_db.getMemberAvatar());
            memberWithBLOBs.setRecommendId(member_db.getRecommendId());
            memberWithBLOBs.setRecommendName(member_db.getRecommendName());
            memberWithBLOBs.setMemberType(member_db.getMemberType());                 //会变化的数据最好不放在session中
            memberWithBLOBs.setProxyId(member_db.getProxyId());
            memberWithBLOBs.setProxyTeamId(member_db.getProxyTeamId());
            //检查用户是否更换过头像或昵称，如果有更新用户头像及昵称，否则更新用户登录信息
            Member mem_upd = new Member();
            mem_upd.setMemberId(member_db.getMemberId());
//            logger.debug("===== member_db:"+member_db.getMemberTruename()+","+member_db.getMemberAvatar());
//            logger.debug("===== wx_user_info:"+userInfo.getNickName()+","+userInfo.getAvatar());
            //用户原本没有头像，现在增加了头像，或微信头像有更新的情况，更新用户名与头像
            if( (member_db.getMemberAvatar()==null && userInfo.getAvatar()!=null) || (member_db.getMemberAvatar()!=null && !member_db.getMemberAvatar().equals(userInfo.getAvatar()))){
                mem_upd.setMemberAvatar(userInfo.getAvatar());
                mem_upd.setMemberTruename(userInfo.getNickName());
                //更新头像后，删除redis的变量，重新生成二维码图片
                memberWithBLOBs.setAvatarChanged(true);
            }
            mem_upd.setMemberName(userInfo.getNickName());
            mem_upd.setMemberLoginNum(member_db.getMemberLoginNum());
            mem_upd.setMemberOldLoginTime(member_db.getMemberLoginTime());
            mem_upd.setMemberLoginTime(DateUtil.unixTimeStamp());
            memberMapper.updateMemberBaseInfo(mem_upd);
        }

        return memberWithBLOBs;
    }

    /**
     * 重写父类方法，微信端获取用户中心信息
     * 包括：基本信息,member_type,proxy相关信息，points等
     * @param userId
     * @return
     */
    @Override
    public Member getUcenterMemberById(Integer userId) {
//        return super.getUcenterMemberById(userId);
        return memberMapper.getMemberById(userId);
    }



}
